package com.testyz.login;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.testandroid1.BuildConfig;
import com.example.testandroid1.R;
import com.testyz.util.EncryptUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class main1 extends AppCompatActivity implements View.OnClickListener{
    EditText username;//http请求触发按钮
    EditText password;//http请求触发按钮
    TextView show;//responseJson显示器
    private String Cookie = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //获得资源页面
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1); //绑定res.layout.main1.xml页面
        //元素绑定事件
        username=(EditText) findViewById(R.id.key);
        password=(EditText) findViewById(R.id.key1);
        show = (TextView) findViewById(R.id.textView1);
        Button login = (Button) findViewById(R.id.button1);
        Button find = (Button) findViewById(R.id.button);
        //开启监视器，监听触发
        login.setOnClickListener(this);
        find.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.button1) {
            //HttpUrlConnection  POST  登陆
            post("https://horsesix.club/user/login");
        }else if(v.getId() == R.id.button) {
            //okhttp  POST  使用登陆后的查找功能
            sendRequestWithOkHttp(Cookie);
        }
    }

    /**
     * POST请求
     *
     * @param requestUrl 请求地址
     * @return
     */
    public void post(String requestUrl) {
        final HttpURLConnection[] connection = {null};
        final InputStream[] is = {null};
        final OutputStream[] os = {null};
        final BufferedReader[] br = {null};
        final String[] result = {null};
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    /** 创建远程url连接对象 */
                    URL url = new URL(requestUrl);
                    /** 通过远程url对象打开一个连接，强制转换为HttpUrlConnection类型 */
                    connection[0] = (HttpURLConnection) url.openConnection();
                    /** 设置连接方式：POST */
                    connection[0].setRequestMethod("POST");
                    /** 设置连接主机服务器超时时间：15000毫秒 */
                    connection[0].setConnectTimeout(3000);
                    /** 设置读取远程返回的数据时间：60000毫秒 */
                    connection[0].setReadTimeout(3000);
                    /** 设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个 */
                    // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
                    connection[0].setDoOutput(true);
                    // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
                    connection[0].setDoInput(true);
                    // 不做缓存
                    connection[0].setUseCaches(false);
                    connection[0].setInstanceFollowRedirects(true);
//                    connection[0].setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    connection[0].setRequestProperty("connection", "Keep-Alive");
                    //获取元素节点中的值
                    final String uname = username.getText().toString().trim();
                    final String pasw = password.getText().toString().trim();
                    // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式
                    String data = "username="+uname+"&password="+EncryptUtil.MD5(pasw);
                    connection[0].setRequestProperty("Content-Length",String.valueOf(data.getBytes().length));
                    /** 通过连接对象获取一个输出流 */
                    connection[0].connect();
                    os[0] = connection[0].getOutputStream();
                    // 设置传输对象信息
                    /** 通过输出流对象将参数写出去/传输出去，它是通过字节数组写出的 */
                    // 若使用os.print(param);则需要释放缓存：os.flush();即使用字符流输出需要释放缓存，字节流则不需要
                    if (data != null && data.length() > 0) {
                        System.out.println("++++++++++++++++++++++++++++++++++++");
                        os[0].write(data.getBytes());
                        os[0].flush();
                        os[0].close();
                    }
                    System.out.println("------------------------------------ ");
                    /** 请求成功：返回码为200 */
                    if (connection[0].getResponseCode() == 200) {
                        System.out.println("-------------oooooooooo--------------- ");
                        /** 通过连接对象获取一个输入流，向远程读取 */
                        is[0] = connection[0].getInputStream();
                        /** 封装输入流is，并指定字符集 */
                        br[0] = new BufferedReader(new InputStreamReader(is[0], "UTF-8"));
                        /** 存放数据 */
                        StringBuffer sbf = new StringBuffer();
                        String line = null;
                        while ((line = br[0].readLine()) != null) {
                            sbf.append(line);
                            sbf.append("\r\n");
                        }
                        result[0] = sbf.toString();
                        showResponse(result[0]);
                        Cookie = connection[0].getHeaderField("Set-Cookie");
                        System.out.println("cookie============="+Cookie);
                    }
//                    Intent in = new Intent(main1.class,logined.class);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    /** 关闭资源 */
                    try {
                        if (null != br[0])
                            br[0].close();
                        if (null != is[0])
                            is[0].close();
                        if (null != os[0])
                            os[0].close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /** 关闭远程连接 */
                    // 断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
                    // 固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些
                    connection[0].disconnect();
                }
            }
        }).start();
    }

    private void sendRequestWithOkHttp(String Cookie) {
        final String uname = username.getText().toString().trim();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url=new URL("https://horsesix.club/user/batch-find");
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("uid", uname)
                            .build();
                    final Request request = new Request.Builder()
                            .url(url)
                            .addHeader("Cookie", Cookie)
                            .post(requestBody)//默认就是GET请求，可以不写
                            .build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            showResponse("请求失败.......");
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (BuildConfig.DEBUG) {
                                final String res = response.body().string();
//                                JSONObject json = JSON.parseObject(res);
                                showResponse("服务器返回json="+res);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作，将结果显示到界面上
                show.setText(response);
            }
        });
    }
}
